define(function(require, exports){
	var $ = require('jquery');
	var pubjs = require('pubjs');
	var view  = require('@base/view');
	var util = require('util');
	var pop = require('admin/smartMonitor/popwin/popwin');

	// 新建/编辑监控
	var Edit = view.container.extend({
		init:function(config){
			config = pubjs.conf(config, {
				'class': 'P-adminSmartMonitor',
				'hasCopyPublic': false,
				'hasFootBtn': true,
				'readonly': false, // 只读模式
				'view_model': {
					'hasCopyPublic': false, // 显示“复制公用条件”按钮
					'hasFootBtn': true, // 显示按钮
					'name':  LANG('新建监控_%1', util.date('YmdHis')), // 名称
					'emails': '', // 联系邮箱
					'remarks': '', // 备注
					'showEmails': false, // 显示联系邮箱
					'readonly': false,
					'status': null
				}
			});

			// 频率数组
			this.$freArr = [
				{ 'name': LANG('每15分钟'), 'id': 15 },
				{ 'name': LANG('每30分钟'), 'id': 30 },
				{ 'name': LANG('每小时'), 'id': 60 },
				{ 'name': LANG('每2小时'), 'id': 120 },
				{ 'name': LANG('每3小时'), 'id': 180 },
				{ 'name': LANG('每6小时'), 'id': 360 },
				{ 'name': LANG('每12小时'), 'id': 720 },
				{ 'name': LANG('每24小时'), 'id': 1440 }
			];

			this.$gridData = [];
			this.$gridIndex = -1;
			this.$data = null;
			this.$cacheData = {};	// 缓存活动和广告位的条件内容
			this.$currentDimType = 1; // 当前DimTYpe
			this.$currentStatus = 1; // 当前Status
			this.$saveas = false;	// 是否另存为

			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			var c = self.getConfig();
			self.vm.$.hasCopyPublic =  c.hasCopyPublic;
			self.vm.$.readonly = c.readonly;
			self.vm.$.hasFootBtn = c.hasFootBtn;

			self.append($([
				'<div class="M-formHead">',
				'</div>',

				'<div class="M-formCon">',

					'<div class="M-formConGroup">',
						'<label class="group-label">'+LANG('名称：')+'</label>',
						'<div class="group-content" ms-class-is-disabled="readonly">',
							'<input type="text" class="w40pct" ms-duplex="name"/>',
							'<span ms-if="hasCopyPublic" pub-name="copy" pub-mod="@base/common/input.button"></span>',
						'</div>',
					'</div>',

					'<div class="M-formConGroup">',
						'<label class="group-label">'+LANG('广告主选择：')+'</label>',
						'<div class="group-content">',
							'<span pub-name="selectAdver" pub-mod="modules/selectAdver.base"></span>',
						'</div>',
					'</div>',

					'<div class="M-formConGroup">',
						'<label class="group-label">'+LANG('维度：')+'</label>',
						'<div class="group-content" ms-class-is-disabled="readonly">',
							'<span pub-name="dimType" pub-mod="@base/common/input.radio"></span>',
						'</div>',
					'</div>',

					'<div class="M-formConGroup">',
						'<label class="group-label">'+LANG('条件内容：')+'</label>',
						'<div class="group-content" ms-class-is-disabled="readonly">',
							'<div class="mb10">',
								LANG('同一条件里多个监控设置为且关系，多个条件之间为或关系'),
							'</div>',
							'<div pub-name="grid" pub-mod="admin/smartMonitor/grid/grid.editList"></div>',
							'<div pub-name="add" pub-mod="@base/common/input.button"></div>',
						'</div>',
					'</div>',

					'<div class="M-formConGroup">',
						'<label class="group-label">'+LANG('监控频率：')+'</label>',
						'<div class="group-content" ms-class-is-disabled="readonly">',
							'<span pub-name="frequency" pub-mod="@base/common/drop.drop" class="mr10"></span>',
							'<span>'+LANG('监控一次')+'</span>',
						'</div>',
					'</div>',

					'<div class="M-formConGroup">',
						'<label class="group-label">'+LANG('操作：')+'</label>',
						'<div class="group-content" ms-class-is-disabled="readonly">',
							'<span pub-name="method" pub-mod="@base/common/input.checkbox"></span>',
						'</div>',
					'</div>',

					'<div class="M-formConGroup" ms-visible="showEmails">',
						'<label class="group-label">'+LANG('联系邮箱：')+'</label>',
						'<div class="group-content" ms-class-is-disabled="readonly">',
							'<textarea class="h100 w40pct mr10" ms-duplex="emails" placeholder="'+ LANG('多个邮箱使用;或换行隔开') + '"></textarea>',
						'</div>',
					'</div>',

					// '<div class="M-formConGroup">',
					// 	'<label class="group-label">'+LANG('备注：')+'</label>',
					// 	'<div class="group-content" ms-class-is-disabled="readonly">',
					// 		'<textarea class="h100 w50pct" ms-duplex="remarks"></textarea>',
					// 	'</div>',
					// '</div>',

					'<div class="M-formConGroup">',
						'<label class="group-label">'+LANG('状态：')+'</label>',
						'<div class="group-content" ms-class-is-disabled="readonly">',
							'<span pub-name="status" pub-mod="@base/common/input.radio"></span>',
						'</div>',
					'</div>',

				'</div>',

				'<div class="M-formButtons" ms-visible="hasFootBtn">',
					'<span pub-name="cancel" pub-mod="@base/common/input.button"></span>',
					'<span pub-name="save" pub-mod="@base/common/input.button" ms-if="!readonly"></span>',
				'</div>'
			].join('')));


			var config = {
				'dimType': {
					'data': [
						{'text': LANG('推广组'), 'id':1, 'value':'campaign', 'checked': true},
						{'text': LANG('广告位'), 'id':2, 'value':'spot'}
					],
					'changeEvent': true
				},
				'frequency': {
					'width': 150,
					'def': LANG('请选择'),
					'options': self.$freArr,
					'panel_config': {
						'hasSearch': false
					}
				},
				'copy': {
					'value': LANG('复制已有条件'),
					'class': 'btn btn-default ml20',
					'width': null
				},
				'selectAdver': {

				},
				'add': {
					'value': LANG('新增条件'),
					'class': 'btn btn-default mt10',
					'width': 100
				},
				'grid': {
					'operation': {
						'width': 90,
						'html': [
							'<a data-op="edit">' + LANG("修改") + '</a>',
							'<a data-op="remove">' + LANG("删除") + '</a>'
						].join(' | ')
					}
				},
				'method': {
					'data': [
						//{'text': LANG('发系统消息'), 'id':'EnableNotice', 'value':'EnableNotice', 'checked': true},
						{'text': LANG('发邮件提醒'), 'id':'EnableEmail', 'value':'EnableEmail'},
						{'text': LANG('暂停推广组'), 'id':'StopCampaign', 'value':'StopCampaign'}
					],
					'changeEvent': true
				},
				'status':{
					'data': [
						{'text': LANG('开启'), 'id': 1 , 'value': 'open' , 'checked': true},
						{'text': LANG('关闭'), 'id': 2 , 'value': 'close'}
					],
					'changeEvent': true
				},
				// 表单取消按钮
				'cancel': {
					'value': LANG('取消'),
					'class': 'btn btn-link mr20'
				},
				// 表单保存按钮
				'save': {
					'value': LANG('保存'),
					'class': 'btn btn-confirm'
				}
			}
			self.buildFromTemplate(config);
		},
		onRadioChange: function(ev){
			if(ev.name == 'dimType'){
				this.$currentDimType = ev.param.id;
				this.setGridData();
			}
			if(ev.name == 'status'){
				this.$currentStatus = ev.param.id;
			}
			return false;
		},
		onCheckboxChange: function(ev){
			// 是否显示联系邮箱
			if(ev.name == 'method'){
				if(ev.param && ev.param.selected){
					this.vm.$.showEmails = util.exist(ev.param.selected, 'EnableEmail');
				}
			}
		},
		// 表格操作列响应
		onListOpClick: function( ev ) {
			var param = ev.param;
			var self = this;
			var op = param.op;
			var data = param.data;
			var index = param.index;
			switch ( op ) {
				case 'edit':
					self.showEditPop(index, data);
				break;
				case 'remove':
					pubjs.confirm(LANG('确定要删除选中的记录吗？'),function(isOk){
						if(isOk){
							self.eventRemove(index);
						}
					});

				break;
			}
			return false;
		},
		onInputClick: function(ev){
			switch (ev.name){
				case 'copy':
					break;
				case 'add':
					this.showEditPop();
					break;
				case 'method':
					break;
				case 'cancel':
					this.cancel();
					break;
				case 'save':
					this.save();
					break;
			}
			return false;
		},
		// 打开弹层
		showEditPop: function(index, data){
			var self = this;
			var dialog = self.get('createNew');
			if(!dialog){
				dialog = self.create('createNew', pop.createNew, {
					'silence': false
				});
			}
			if(!data){
				// 新建状态
				dialog.reset().setDimType(self.$currentDimType).show();
				// 更改gridIndex状态
				self.$gridIndex = -1;
			}else{
				// 编辑状态
				// 更改gridIndex状态
				self.$gridIndex = index;
				dialog.setData(data).show();
			}
			return self;
		},
		getData: function(){
			var self = this;
			var mod = self.$;
			var vm = self.vm.$;
			var method = mod['method'].getData();
			var id = '';
			// 另存为模式
			if(self.$saveas){
				id = 0;
			}else{
				id = self.$data && self.$data._id || 0;
			}

			// 重新处理一下Emails
			var Emails = [];
			util.each(vm['emails'].replace(/(\n)+|(\r\n)+|(；)+|(;)/g, '\n').split('\n'), function(item){
				if(util.trim(item)){
					Emails.push(util.trim(item));
				}
			});

			// 重新处理一下Conditions
			var Conditions = [];
			util.each(self.$cacheData[self.$currentDimType], function(item){
				if(item && item.Conditions && item.Conditions.length){
					Conditions.push(item.Conditions);
				}
			});

			var result = {
				'_id': id,
				'Name': vm.name,
				'Frequency': +mod['frequency'].getValue(true)['id'],
				'DimType': self.$currentDimType, // 推广组: 1,广告位: 2
				'Conditions': Conditions, // 条件内容
				// 'Grant': self.$data && self.$data.Grant || [], // 授权
				// 'Status': self.$data && self.$data.Status || 0, // 运行中: 1, 暂停中: 0
				'AdvertiserId': mod.selectAdver.getData(),
				'EnableEmail': util.exist(method, 'EnableEmail'),
				//'EnableNotice': util.exist(method, 'EnableNotice'),
				'StopCampaign': util.exist(method, 'StopCampaign'),
				'Emails': Emails,
				'Status': self.$currentStatus,
				// 'Remarks': vm.remarks
			}

			return result;
		},
		setData: function(data){
			if(data){
				var self = this;
				var mod = self.$;
				var vm = self.vm.$;

				self.$data = data;
				vm.name = data.Name || '',
				vm.emails = data.Emails && data.Emails.join(';\n') || '';
				// vm.remarks = data.Remarks;
				mod['frequency'].setValue(data.Frequency);
				mod['dimType'].setData(data.DimType);
				mod['status'].setData(data.Status);
				self.$currentDimType = data.DimType;
				self.$currentStatus = data.Status;

				var gridData = [];
				util.each((data.Conditions || data.Rules || []), function(item){
					if(item){
						gridData.push({
							'Conditions': item,
							'DimType': data.DimType
						});
					}
				});
				self.$cacheData[self.$currentDimType] = gridData;
				// 更新列表条件
				self.setGridData();

				var method = [];
				if(data.EnableEmail){
					method.push('EnableEmail');
					vm.showEmails = true;
				}
/*				if(data.EnableNotice){
					method.push('EnableNotice');
				}*/
				if(data.StopCampaign){
					method.push('StopCampaign');
				}
				mod['method'].setData(method);
				mod['selectAdver'].setData((data.AdvertiserId) ? data.AdvertiserId : []);
				//更新广告主选择组件
			}
		},
		load: function(id, saveas){
			var self = this;
			// 是否另存为
			self.$saveas = saveas ? true : false;
			self.showLoading();
			pubjs.mc.send('monitor/infoAlarm', {
				'_id': id
			}, self.onData.bind(self));
			return self;
		},
		onData: function(err, data) {
			this.hideLoading();
			if (err) {
				pubjs.error(err.message);
				pubjs.alert(err.message);
				return false;
			}
			this.setData(data);
		},
		save: function(cb){
			var data = this.getData();
			if(!data.Name){
				pubjs.alert(LANG('请填写监控设置名称!'));
				return false;
			}
			if(data.Conditions && !data.Conditions.length){
				pubjs.alert(LANG('请设置监控条件!'));
				return false;
			}
			if(!data.Frequency){
				pubjs.alert(LANG('请选择监控频率!'));
				return false;
			}
			if(data.EnableEmail && !data.Emails.length){
				pubjs.alert(LANG('请填写邮箱地址!'));
				return false;
			}
			if(data.Emails.length){
				var err = false;
				util.each(data.Emails, function(item){
					if(item && !util.isEmail(item)){
						err = true;
						return;
					}
				});
				if(err){
					pubjs.alert(LANG('请填写正确的邮箱地址格式!'));
					return false;
				}
			}
			// if()

			this.showLoading();
			var url = data._id ? 'monitor/updateAlarm' : 'monitor/addAlarm';
			pubjs.mc.send(
				url,
				data,
				this[cb || 'afterSave'].bind(this)
			);
			return false;
		},
		afterSave: function(err, data){
			this.hideLoading();
			if (err) {
				return pubjs.alert(err.message);
			}
			pubjs.alert(LANG("保存成功"));
			this.cancel();
			this.fire('saveMonitorSuccess', {'data': data});
		},
		afterPopSave: function(err, data){
			this.hideLoading();
			if (err) {
				return pubjs.alert(err.message);
			}
			pubjs.alert(LANG("保存成功"));
			this.fire('saveMonitorPopSuccess', {'data': data});
		},
		cancel: function(){
			pubjs.controller.navigate('admin/smartMonitor');
		},
		eventRemove: function(index){
			var self = this;
			self.$cacheData[self.$currentDimType].splice(index, 1);
			self.setGridData();
		},
		// 添加条件后接收广播
		onAddConditionSelected: function(ev){
			var self = this;
			var cacheData = self.$cacheData;
			var dimType = self.$currentDimType;
			if(!cacheData[dimType]){
				cacheData[dimType] = [];
			}
			var gridData = cacheData[dimType];

			// 为了方便列表渲染，组合一下数据为对象格式
			var data = {
				DimType: dimType,
				Conditions: ev.param
			};

			if(this.$gridIndex === -1){
				gridData.push(data);
			}else{
				gridData.splice(this.$gridIndex, 1, data);
			}
			this.setGridData();
		},
		// 设置表格数据
		setGridData: function(data){
			var self = this;
			var grid = self.get('grid');
			grid.setData(self.$cacheData[self.$currentDimType]);
			return self;
		},
		reset: function(){
			var self = this;
			self.vm.reset();
			self.vm.$.name = LANG('新建监控_%1', util.date('YmdHis'));
			self.$.dimType.setData(1);
			self.$.status.setData(1);
			self.$.frequency.reset();
			self.$.grid.setData([]);
			//self.$.method.setData(['EnableNotice']);
			self.$.method.reset();
			self.$.selectAdver.reset();
			self.$gridData = [];
			self.$data = null;
			self.$gridIndex = -1;
			self.$saveas = false;
			self.$cacheData = {};	// 缓存活动和广告位的条件内容
			self.$currentDimType = 1; // 当前DimTYpe
			return self;
		}
	});
	exports.edit = Edit;
});